package com.heyqing.medium.day12;

/**
 * ClassName:FindClosedNumbers
 * Package:com.heyqing.medium.day12
 * Description:
 *
 * @Date:2024/10/14
 * @Author:Heyqing
 */
public class FindClosedNumbers {
    public int[] findClosedNumbers(int num) {
        if (num == 2147483647) return new int[]{-1, -1};
        if (num == 1) return new int[]{2, -1};
        int nc = calculate(num);
        int[] res = new int[]{-1, -1};
        for (int i = num - 1; i >= 1; i--) {
            if (nc == calculate(i)) {
                res[1] = i;
                break;
            }
        }
        for (int i = num + 1; i < Integer.MAX_VALUE; i++) {
            if (nc == calculate(i)) {
                res[0] = i;
                break;
            }
        }
        return res;
    }

    private int calculate(int n) {
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & 1) == 1) count++;
            n >>= 1;
        }
        return count;
    }
}
